package com.lagou.edu.listener;

import com.lagou.edu.factory.BeanFactory;
import com.mysql.jdbc.StringUtils;

import javax.servlet.*;

/**
 * IoC容器初始化监听器
 */
public class ContextLoaderListener implements ServletContextListener {
    /**
     * 初始化IoC容器
     * @param sce
     */
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext servletContext = sce.getServletContext();
        try {
            servletContext.log("Init lagou-transfer-anno Start");
            // 配置类
            String contextConfig = servletContext.getInitParameter("contextConfig");
            if(StringUtils.isNullOrEmpty(contextConfig)) {
                throw new RuntimeException("not found contextConfig");
            }
            // 初始化IoC容器
            new BeanFactory(contextConfig, servletContext);
            servletContext.log("Init lagou-transfer-anno Success");
        } catch (Exception e) {
            servletContext.log("Init lagou-transfer-anno Fail : " + e);
            contextDestroyed(sce);
        }
    }

    /**
     * 初始化失败 停止启动
     * @param sce
     */
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        ServletContext servletContext = sce.getServletContext();
        servletContext.log("stop lagou-transfer-anno Start");
        System.exit(0);
    }
}
